<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use app\common\model\Bank;
use think\Hook;
use think\Db;
use app\api\model\Address;
use app\common\library\Sms as Smslib;
use app\common\library\Ems as Emslib;
/**
 * 会员接口
 */
class User extends Api
{

    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        //注册钩子 用于重置会员矿机
        Hook::add('user_login_successed', function ($user) {
            if ($user->prevtime<strtotime(date('Ymd'))) {
                Db::name('mineral')->where('user_id',$user->id)->where('status','running')->setField('already',0); // 重置矿机
                // Db::name('mineral')->where('user_id',$user->id)->where('expiretime','< time',time())->setField('status','scrapped');  //将过期矿机销毁
                $num = Db::name('mineral')->where('user_id',$user->id)->where('status','running')->sum('num'); //查询是否还有矿机在运行  没有则改为未激活状态
                if ($num == 0) {
                    $user->active = 0 ;
                    $user->save();
                }
            }
        });
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->auth->getUserToken();
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    public function userinfo()
    {
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('获取成功'), $data);
    }

    /**
     * 会员登录
     * 
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account','','strtolower');
        $password = $this->request->request('password');
        if (!$account || !$password)
        {
            $this->error(__('Invalid parameters'));
        }

        if (config('site.member_login') == 'close') {
            $this->error(__('系统升级维护中'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret)
        {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     * 
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin'))
        {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user)
        {
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }
        else
        {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret)
        {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     * 
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $paypassword 支付密码
     * @param string $refer_username 推荐人用户名
     * @param string $mobile 手机号
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $paypassword = $this->request->request('paypassword');
        $captcha = $this->request->request('captcha');
       
        $account = $this->request->request('account','');
        $refer_username = $this->request->request('refer_username',0);
        if (!$username || !$password)
        {
            $this->error(__('Invalid parameters'));
        }
        $email='';
        if (Validate::is($account, "email"))
        {
            $email = $account;
        }
        $mobile='';
        if (Validate::regex($account, "^1\d{10}$"))
        {
            $mobile = $account;
            if(config('site.user_sms_check') == 'open'){
                $ret = Smslib::check($mobile, $captcha, 'smsCode');
                if (!$ret) {
                    $this->error(__('验证码不正确'));
                }
            }
        }
        if (!$password) {
            $this->error(__('请输入密码'));
        }
        if (!$paypassword) {
            $this->error(__('请输入支付密码'));
        }

        if (!Validate::regex($username,"^[a-zA-Z][a-zA-Z0-9_]{3,24}$")) {
            $this->error(__('用户名不能以数字开头并且不能少于4个字符'));
        }
        $user_id = decodeInvite($refer_username);
        $exists = \app\common\model\User::where('id', $user_id)->where('status','normal')->find();
        if (!$exists)
        {
            $this->error(__('推荐人不存在'));
        }
        if ($exists->level == 0) {
            $this->error(__('推荐人不是正式会员'));
        }

        $ret = $this->auth->register($username, $password, $email, $mobile, ['referee_id'=>$exists->id,'plaintext'=>$password,'payplaintext'=>$paypassword]);
        if ($ret)
        {
            $data = ['userinfo' => $this->auth->getUserinfo(),'token'=>$this->auth->getUserToken()];
            $this->success(__('Sign up successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     * 
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar');
        $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        if ($exists)
        {
            $this->error(__('Username already exists'));
        }
        $user->username = $username;
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }
    /**
     * 修改会员个人信息 某字段
     * @ApiParams   (name="field", type="string", required=true, description="要修改的字段 nickname,realname,idcard,alipay,wechatwallet,bio,avatar,gender")
     * @ApiParams   (name="value", type="string", required=true, description="要修改的字段值")
     */
    public function profilesingle()
    {
        $fieldallow = ['nickname','realname','idcard','alipay','wechatwallet','bio','avatar','gender','eth','mobile','email'];
        $user = $this->auth->getUser();
        $field = $this->request->request('field');
        if (!in_array($field, $fieldallow)) {
            $this->error('字段不允许修改');
        }
        if ($field == 'eth') {
            $captcha = $this->request->request("captcha");
            $userinfo = $this->auth->getUserInfo();
            if ($userinfo['mobile']) {
                $ret = Smslib::check($userinfo['mobile'], $captcha, 'USDT');
                if (!$ret) {
                    $this->error(__('验证码不正确'));
                }
            }else{
                $this->error(__('验证码不正确'));
            }
            $memo = $this->request->request('memo');
            $user->memo = $memo;
        }
        $value = $this->request->request('value','','trim');
        if (empty($value)) {
            $this->error('请填写');
        }
        $user->$field = $value;
        $user->save();
        $this->success('成功');
    }
    /**
     * 修改邮箱
     * 
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email"))
        {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find())
        {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result)
        {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     * 
     * @param string $email 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha)
        {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$"))
        {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find())
        {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result)
        {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     * 
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform]))
        {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result)
        {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret)
            {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     * 
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $account = $this->request->request("account",'17649608685');
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");

        $user  = Db::name('user')->where('email|mobile',$account)->field('id,email,mobile')->find();
        if (!$user) {
            $this->error('账号不存在');
        }

        if (Validate::is($account, "email")) {

            $this->success('已将账号密码发送至邮箱');

        }elseif(Validate::regex($account, "^1\d{10}$")){
            $ret = Sms::check($account, $captcha, 'resetpwd');
            if (!$ret)
            {
                $this->error(__('Captcha is incorrect'));
            }
            $this->auth->direct($user['id']);
            $ret = $this->auth->changepwd($newpassword, '', true);
            $this->success('重置密码成功');
        }else{
            $this->error(__('账户不正确'));
        }



        // $type = $this->request->request("type");
        // $mobile = $this->request->request("mobile");
        // $email = $this->request->request("email");
        // $newpassword = $this->request->request("newpassword");
        // $captcha = $this->request->request("captcha");
        // if (!$newpassword || !$captcha)
        // {
        //     $this->error(__('Invalid parameters'));
        // }

        //     if (!Validate::regex($mobile, "^1\d{10}$"))
        //     {
        //         $this->error(__('Mobile is incorrect'));
        //     }
        //     $user = \app\common\model\User::getByMobile($mobile);
        //     if (!$user)
        //     {
        //         $this->error(__('User not found'));
        //     }
        //     $ret = Sms::check($mobile, $captcha, 'resetpwd');
        //     if (!$ret)
        //     {
        //         $this->error(__('Captcha is incorrect'));
        //     }
        //     Sms::flush($mobile, 'resetpwd');

        //     if (!Validate::is($email, "email"))
        //     {
        //         $this->error(__('Email is incorrect'));
        //     }
        //     $user = \app\common\model\User::getByEmail($email);
        //     if (!$user)
        //     {
        //         $this->error(__('User not found'));
        //     }
        //     $ret = Ems::check($email, $captcha, 'resetpwd');
        //     if (!$ret)
        //     {
        //         $this->error(__('Captcha is incorrect'));
        //     }
        //     Ems::flush($email, 'resetpwd');
        // //模拟一次登录
        // $this->auth->direct($user->id);
        // $ret = $this->auth->changepwd($newpassword, '', true);
        // if ($ret)
        // {
        //     $this->success(__('Reset password successful'));
        // }
        // else
        // {
        //     $this->error($this->auth->getError());
        // }
    }

    /**
     * 重置密码  使用旧密码来修改的方式
     * 
     * @param string $oldpassword 旧密码
     * @param string $newpassword 新密码
     * @param string $confirmpassword 确认密码
     */
    public function resetpasswrod()
    {
        $oldpassword = $this->request->request("oldpassword");
        $newpassword = $this->request->request("newpassword");
        $confirmpassword = $this->request->request("confirmpassword");
        $captcha = $this->request->request("captcha");
        $userinfo = $this->auth->getUserInfo();
        if ($userinfo['mobile']) {
            $ret = Smslib::check($userinfo['mobile'], $captcha, 'resetpasswrod');
            if (!$ret) {
                $this->error(__('验证码不正确'));
            }
        }else{
            $this->error(__('验证码不正确'));
        }
        
        

        if (empty($confirmpassword)||empty($newpassword)) {
            $this->error('请输入新密码');
        }
        if ($newpassword !== $confirmpassword) {
            $this->error('确认密码不正确');
        }

        $ret = $this->auth->changepwd($newpassword, $oldpassword,true);
        if ($ret)
        {
            $this->success(__('Reset password successful'));
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 重置支付密码  使用旧密码来修改的方式
     * 
     * @param string $oldpaypassword 旧密码
     * @param string $newpaypassword 新密码
     * @param string $confirmpaypassword 确认密码
     */
    public function resetpaypasswrod()
    {
        $oldpaypassword = $this->request->request("oldpaypassword",'');
        $newpaypassword = $this->request->request("newpaypassword");
        $confirmpaypassword = $this->request->request("confirmpaypassword");
        $captcha = $this->request->request("captcha");

        $userinfo = $this->auth->getUserInfo();
        if ($userinfo['mobile']) {
            $ret = Smslib::check($userinfo['mobile'], $captcha, 'resetpaypasswrod');
            if (!$ret) {
                $this->error(__('验证码不正确'));
            }
        }else{
            $this->error(__('验证码不正确'));
        }

        
        if (empty($newpaypassword)||empty($confirmpaypassword)) {
            $this->error('请输入新密码');
        }
        
        if ($newpaypassword !== $confirmpaypassword) {
            $this->error('确认密码不正确');
        }

        $ret = $this->auth->changeppwd($newpaypassword, $oldpaypassword,true);
        if ($ret)
        {
            $this->success(__('Reset password successful'));
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 获取我的银行卡列表
     * 
     */
    public function getbanks()
    {
        $bank = new Bank();
        $banks=$bank->where('status',1)->where('user_id',$this->auth->id)->order('default desc,id desc')->select();
        $this->success('获取成功',['list'=>$banks]);
    }
    
    /**
     * 可以直接由列表数据传过页面  不需要在调此接口
     * 看框架是否可以页面传值
     * 
     * @param int $id 银行卡id
     */
    public function getbank()
    {
        $id = $this->request->request('id',0);
        $bank = new Bank();
        $info=$bank->where('user_id',$this->auth->id)->where('id',$id)->find();
        if (!$info) {
            $this->error('不是你的银行卡！');
        }
        $this->success('获取成功',['info'=>$info]);
    }

    
    /**
     * 添加银行卡
     * 
     * @param string $bankname 银行名称
     * @param string $bankcard 银行卡
     * @param string $bankaddress 开户地址
     * @param string $realname 开户名
     * @param int $default 是否默认
     */
    public function addbank()
    {
        $bank = new Bank();
        $request = $this->request->request();
        $bank->user_id=$this->auth->id;
        $result = $bank->allowField(true)->validate('Bank.add')->save($request);
        if(false === $result){
            $this->error($bank->getError());
        }
        $this->success('增加成功');
    }

    /**
     * 编辑银行卡
     * 
     * @param string $bankname 银行名称
     * @param string $bankcard 银行卡
     * @param string $bankaddress 开户地址
     * @param string $realname 开户名
     * @param int $default 是否默认
     * @param int $id 索引
     */
    public function editbank()
    {
        $bank = new Bank();
        $request = $this->request->request();
        if (empty($request['id'])) {
            $this->error('请传入id ');
        }
        $bank->user_id=$this->auth->id;
        $result = $bank->allowField(true)->validate('Bank.edit')->save($request,['id'=>$request['id']]);
        if(false === $result){
            $this->error($bank->getError());
        }
        $this->success('修改成功');
    }


    /**
     * 删除银行卡
     * 
     * @param int $id 索引
     */
    public function delbank()
    {
        
        $id = $this->request->request('id');
        if (empty($id)) {
            $this->error('请传入id ');
        }
        $bank = Bank::get(['user_id'=>$this->auth->id,'id'=>$id]);
        if ($bank->default==1) {
            $this->error('无法删除默认银行卡');
        }
        $bank->delete();
        $this->success('删除成功');
    }


    /**
     * 获取我的地址列表
     * 
     */
    public function getaddresss()
    {
        $address = new Address();
        $addresss=$address->where('status',1)->where('user_id',$this->auth->id)->order('default desc,id desc')->select();
        $this->success('获取成功',['list'=>$addresss]);
    }
    
    /**
     * 可以直接由列表数据传过页面  不需要在调此接口
     * 看框架是否可以页面传值
     * 
     * @param int $id 地址id
     */
    public function getaddress()
    {
        $id = $this->request->request('id',0);
        $address = new Address();
        $info=$address->where('user_id',$this->auth->id)->where('id',$id)->find();
        if (!$info) {
            $this->error('不是你的地址！');
        }
        $this->success('获取成功',['info'=>$info]);
    }

    
    /**
     * 添加地址
     * 
     * @param string $consignee 收货人
     * @param string $phone 联系人电话
     * @param string $province 省
     * @param string $city 城市
     * @param string $district 区域
     * @param string $detail 详细地址
     * @param int $default 是否默认
     */
    public function addaddress()
    {
        $address = new Address();
        $request = $this->request->request();
        $address->user_id=$this->auth->id;
        $result = $address->allowField(true)->validate('Address.add')->save($request);
        if(false === $result){
            $this->error($address->getError());
        }
        $this->success('增加成功');
    }
    function getUserinfo($value='')
    {
        
    }
    /**
     * 编辑地址
     * 
     * @param string $consignee 收货人
     * @param string $phone 联系人电话
     * @param string $province 省
     * @param string $city 城市
     * @param string $district 区域
     * @param string $detail 详细地址
     * @param int $default 是否默认
     * @param int $id 索引
     */
    public function editaddress()
    {
        $address = new Address();
        $request = $this->request->request();
        if (empty($request['id'])) {
            $this->error('请传入id ');
        }
        $address->user_id=$this->auth->id;
        $result = $address->allowField(true)->validate('Address.edit')->save($request,['id'=>$request['id']]);
        if(false === $result){
            $this->error($address->getError());
        }
        $this->success('修改成功');
    }


    /**
     * 删除地址
     * 
     * @param int $id 索引
     */
    public function deladdress()
    {
        
        $id = $this->request->request('id');
        if (empty($id)) {
            $this->error('请传入id ');
        }
        $address = Address::get(['user_id'=>$this->auth->id,'id'=>$id]);
        if ($address->default==1) {
            $this->error('无法删除默认银行卡');
        }
        $address->delete();
        $this->success('删除成功');
    }

    public function share()
    {
        $invitecode = createInvite($this->auth->id);
        $this->success('获取成功',['invitecode'=>$invitecode]);
    }

    /**
     * 发送验证码
     * @param  [type] $event [description]
     * @return [type]        [description]
     */
    public function sendCode()
    {
        $event = $this->request->request('event');
        $userinfo = $this->auth->getUserInfo();
        if ($userinfo['mobile']) {
            $ret = Smslib::send($userinfo['mobile'], NULL, $event);
        }elseif($userinfo['email']){
            $ret = Emslib::send($userinfo['userinfo'], NULL, $event);
        }else{
             $this->error(__('发送失败 code：001'));
        }
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败 code：002'));
        }
    }

    public function getUserBaseInfo()
    {
        $username = $this->request->request('username');

        $user = \app\common\model\User::where('username', $username)->find();
        // $this->error(__('发送失败 code：002'));
        if (!$user) {
            $this->error(__('会员不存在'));
        }else{
            $this->success('返回成功',['info'=>['mobile'=>$user['mobile'],'email'=>$user['email']]]);
        }
    }
}
